import { Button, Form, Input, Popconfirm, Switch, Tag, Tree } from "antd";
import {
  FolderOutlined,
  EditOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import CommonPage from "@/components/page/CommonPage";

import styled from "styled-components";
import Add from "@/components/svg/action-slot-icon/Add";
import DeleteOne from "@/components/svg/action-slot-icon/Delete_One";
import CrudTable from "@/components/table/CrudTable";
import QueryBarItem from "@/components/query-bar/QueryBarItem";
import useMyContext from "@/hooks/useContext";
import { useEffect, useRef, useState } from "react";
import useGetState from "@/hooks/useGetState";
import useCRUD from "@/hooks/useCRUD";
import { deleteRole, getRoles, saveOrUpdateRole } from "@/api/role";
import { formatDate } from "@/utils/common/common";
import CrudModal from "@/components/table/CrudModal";
import { getResourceOption } from "@/api/resource";
import { getMenuOption } from "@/api/menu";
const Styled = styled.div``;

const Role = () => {
  const { messageApi } = useMyContext();
  const $table = useRef();
  //搜索框参数
  const [queryItems, setQueryItems, getQueryItems] = useGetState({});
  //所有switch的状态loading管理
  const [loadingStates, setLoadingStates] = useState({});

  //菜单，资源，跳出的菜单不同
  const [showMenu, setShowMenu] = useState(true);
  const [resourceOption, setResourceOption] = useState([]);
  const [menuOption, setMenuOption] = useState([]);

  const [expandedKeys, setExpandedKeys] = useState([]); //默认展开的列表
  const [checkedKeys, setCheckedKeys] = useState([]); //选中收集的列表数据
  const [autoExpandParent, setAutoExpandParent] = useState(true);

  function updateQueryItems(newQueryItems) {
    setQueryItems(newQueryItems);
  }

  const {
    modalVisible,
    setModalVisible,
    modalAction,
    setModalAction,
    modalLoading,
    setModalLoading,
    handleAdd,
    handleDelete,
    handleEdit,
    handleSave,
    modalForm,
    setModalForm,
    modalFormRef,
    modalTitle,
    clearFormFields,
  } = useCRUD({
    name: "角色",
    initForm: {},
    doCreate: saveOrUpdateRole,
    doDelete: deleteRole,
    doUpdate: saveOrUpdateRole,
    refresh: () => $table.current.handleSearch(),
  });

  const columns = [
    {
      title: "角色名",
      key: "name",
      width: 80,
      align: "center",
      ellipsis: { showTitle: true },
      render(_, record) {
        return <>{record.name}</>;
      },
    },
    {
      title: "角色标签",
      key: "label",
      width: 80,
      align: "center",
      render(_, record) {
        return <Tag color="processing">{record.label}</Tag>;
      },
    },
    {
      title: "创建日期",
      key: "created_at",
      width: 60,
      align: "center",
      render(_, reocrd) {
        return <span>{formatDate(reocrd.created_at)}</span>;
      },
    },
    {
      title: "是否禁用",
      key: "is_disable",
      width: 30,
      align: "center",

      render(_, record) {
        return (
          <Switch
            size="small"
            checked={record.is_disable}
            loading={!!loadingStates[record.id]}
            onClick={() => messageApi.info("该功能暂时未完善~")}
          />
        );
      },
    },
    {
      title: "操作",
      key: "actions",
      width: 100,
      align: "center",
      fixed: false,
      render(_, record) {
        return (
          <>
            <>
              <Button
                type="link"
                style={{
                  marginRight: "5px",
                }}
                icon={<EditOutlined />}
                onClick={() => {
                  setShowMenu(true);
                  //显示菜单资源
                  setCheckedKeys(record.menu_ids);
                  setExpandedKeys(record.menu_ids);
                  getMenuOption().then((res) => {
                    setMenuOption(res.data);
                  });
                  handleEdit(record);
                }}
              >
                菜单权限
              </Button>
              <Button
                type="link"
                style={{ marginRight: "5px" }}
                icon={<FolderOutlined />}
                onClick={() => {
                  setShowMenu(false);
                  //显示资源列表
                  setCheckedKeys(record.resource_ids);
                  setExpandedKeys(record.resource_ids);
                  getResourceOption().then((res) => {
                    setResourceOption(res.data);
                  });
                  handleEdit(record);
                }}
              >
                资源权限
              </Button>
              <Popconfirm
                title="确定删除该角色吗"
                onConfirm={() => {
                  handleDelete([record.id]);
                }}
                okText="确认"
                cancelText="取消"
              >
                <Button
                  type="link"
                  icon={<DeleteOutlined />}
                  style={{ color: "#D03050FF" }}
                >
                  删除
                </Button>
              </Popconfirm>
            </>
          </>
        );
      },
    },
  ];

  useEffect(() => {
    //三个获取数据异步进行
    $table.current.handleSearch();
    getResourceOption().then((res) => {
      setResourceOption(res.data);
    });
    getMenuOption().then((res) => {
      setMenuOption(res.data);
    });
  }, []);

  const onExpand = (expandedKeysValue) => {
    setExpandedKeys(expandedKeysValue);
    setAutoExpandParent(false);
  };
  const onCheck = (checkedKeysValue, flag) => {
    setCheckedKeys(checkedKeysValue);
    if (flag === "menu_ids") {
      setModalForm({
        ...modalForm,
        menu_ids: checkedKeysValue,
      });
    } else {
      setModalForm({
        ...modalForm,
        resource_ids: checkedKeysValue,
      });
    }
    setAutoExpandParent(true);
  };

  return (
    <Styled>
      <CommonPage title="角色管理">
        <div className="action-slot" slot="action">
          <Button type="primary" icon={<Add />} onClick={handleAdd}>
            新增角色
          </Button>
        </div>
        <CrudTable
          ref={$table}
          columns={columns}
          queryItems={queryItems}
          updateQueryItems={updateQueryItems}
          getQueryItems={getQueryItems}
          getData={getRoles}
          hasRowSelection={false}
        >
          <div className="queryBar-slot flex label-ml-15" slot="queryBar">
            <QueryBarItem label="角色名" labelWidth={50}>
              <Input
                placeholder="请输入角色名"
                value={queryItems.keyword}
                allowClear
                onChange={(e) => {
                  setQueryItems({
                    ...queryItems,
                    keyword: e.target.value,
                  });
                }}
                onKeyUp={(e) => {
                  if (e.key === "Enter") {
                    $table.current.handleSearch();
                  }
                  if (e.key === "Backspace") {
                    $table.current.handleSearch();
                  }
                }}
              />
            </QueryBarItem>
          </div>
        </CrudTable>
        <CrudModal
          visible={modalVisible}
          setModalVisible={setModalVisible}
          loading={modalLoading}
          title={modalTitle}
          handleSave={handleSave}
          clearFormFields={clearFormFields}
        >
          <Form
            name="role"
            form={modalFormRef}
            labelAlign="left"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
            disabled={modalAction === "view"}
          >
            <Form.Item label="角色名" name="name">
              <Input
                allowClear
                placeholder="请输入角色名称"
                value={modalForm.name}
                onChange={(e) => {
                  setModalForm({
                    ...modalForm,
                    name: e.target.value,
                  });
                }}
              />
            </Form.Item>
            <Form.Item label="角色标签" name="label">
              <Input
                allowClear
                placeholder="请输入角色标签"
                value={modalForm.label}
                onChange={(e) => {
                  setModalForm({
                    ...modalForm,
                    label: e.target.value,
                  });
                }}
              />
            </Form.Item>
            {showMenu ? (
              <Form.Item label="菜单权限" name="menu_ids">
                <Tree
                  checkable
                  onExpand={onExpand} //展开/收起节点时触发
                  expandedKeys={expandedKeys} //展开的树节点
                  treeData={menuOption}
                  checkedKeys={checkedKeys}
                  autoExpandParent={autoExpandParent} //是否自动展开父节点
                  onCheck={(val) => {
                    onCheck(val, "menu_ids");
                  }} //点击复选框触发
                />
              </Form.Item>
            ) : (
              <Form.Item label="资源权限 " name="resource_ids">
                <Tree
                  checkable
                  onExpand={onExpand} //展开/收起节点时触发
                  expandedKeys={expandedKeys} //展开的树节点
                  treeData={resourceOption}
                  checkedKeys={checkedKeys}
                  autoExpandParent={autoExpandParent} //是否自动展开父节点
                  onCheck={(val) => {
                    onCheck(val, "resource_ids");
                  }} //点击复选框触发
                />
              </Form.Item>
            )}
          </Form>
        </CrudModal>
      </CommonPage>
    </Styled>
  );
};

export default Role;
